<!--
  * 公司列表
  *
  * @Author:    1024创新实验室-主任：卓大
  * @Date:      2022-08-15 20:15:49
  * @Wechat:    zhuda1024
  * @Email:     lab1024@163.com
  * @Copyright  1024创新实验室 （ https://1024lab.net ），Since 2012
-->
<template>
    <a-form class="smart-query-form" v-privilege="'oa:enterprise:query'">
      <a-row class="smart-query-form-row">
        <a-form-item label="车辆属性" class="smart-query-form-item">
          <a-select
          style="width: 300px"
            v-model:value="queryForm.carCode"
                placeholder="请选择"
                :options="[{value:'单位',label:'单位'},{value:'个人',label:'个人'}]"
           >
           </a-select>
        </a-form-item>
        <a-form-item label="车牌" class="smart-query-form-item">
          <a-input style="width: 300px" v-model:value="queryForm.carPlate" placeholder="请输入车牌" />
        </a-form-item>
        <!-- <a-form-item label="标签号" class="smart-query-form-item">
          <a-input style="width: 300px" v-model:value="queryForm.tag" placeholder="请输入标签号" />
        </a-form-item> -->
  
        <a-form-item class="smart-query-form-item smart-margin-left10">
          <a-button-group>
            <a-button type="primary" @click="onSearch">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetQuery">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-button-group>
        </a-form-item>
      </a-row>
    </a-form>
  
    <a-card size="small" :bordered="false" :hoverable="true">
      <a-row class="smart-table-btn-block">
        <div class="smart-table-operate-block">
            <a-button @click="addForms" type="primary" v-privilege="'transit:plateNumber:add'">
          <template #icon>
            <PlusOutlined />
          </template>
          新建
        </a-button>
        <a-button @click="showImportModal" type="primary" v-privilege="'transit:plateNumber:import'">
          <template #icon>
            <ImportOutlined />
          </template>
          导入
        </a-button>
          <a-button @click="exportExcel()" v-privilege="'transit:plateNumber:exportExcel'" type="primary">
            <template #icon>
              <FileExcelOutlined />
            </template>
            导出
          </a-button>
        </div>
        <div class="smart-table-setting-block">
          <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.LICENSE_PLATE_RECOGNITIONG.LICENSE_PLATE_MANAGEMENT" :refresh="ajaxQuery" />
        </div>
      </a-row>
  
      <a-table
        size="small"
        :dataSource="tableData"
        :columns="columns"
        rowKey="enterpriseId"
        :pagination="false"
        :loading="tableLoading"
        bordered
      >
        <template #bodyCell="{ column, record, text }">
          <template v-if="column.dataIndex === 'status'">
            {{['不可通行','可通行',''][text] }}
          </template>
          
          <template v-if="column.dataIndex === 'whitelistIp'">
            {{whitelistIpFn(record) }}
          </template>
          <template v-if="column.dataIndex === 'action'">
            <div class="smart-table-operate">
              <a-button @click="updateForms(record)" size="small" v-privilege="'transit:plateNumber:update'" type="link">编辑</a-button>
              <a-button @click="confirmDelete(record.id)" size="small" danger v-privilege="'transit:plateNumber:delete'" type="link">删除</a-button>
            </div>
          </template>
        </template>
      </a-table>
  
      <div class="smart-query-table-page">
        <a-pagination
          showSizeChanger
          showQuickJumper
          show-less-items
          :pageSizeOptions="PAGE_SIZE_OPTIONS"
          :defaultPageSize="queryForm.pageSize"
          v-model:current="queryForm.pageNum"
          v-model:pageSize="queryForm.pageSize"
          :total="total"
          @change="ajaxQuery"
          @showSizeChange="ajaxQuery"
          :show-total="(total) => `共${total}条`"
        />
      </div>
      <!-- <EnterpriseOperate ref="operateRef" @refresh="ajaxQuery" /> -->
      <Form ref="formModal" @reloadList="ajaxQuery" />

      
      <!-- 导入窗口 -->
      
    <a-modal v-model:open="importModalShowFlag" title="导入" @onCancel="hideImportModal" @ok="hideImportModal">
      <div style="text-align: center; width: 400px; margin: 0 auto">
        <a-button @click="downloadExcel"> <download-outlined />第一步：下载模板</a-button>
        <br />
        <br />
        <a-upload
          v-model:fileList="fileList"
          name="file"
          :multiple="false"
          action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
          accept=".xls,.xlsx"
          :before-upload="beforeUpload"
          @remove="handleRemove"
        >
          <a-button>
            <upload-outlined />
            第二步：选择文件
          </a-button>
        </a-upload>

        <br />
        <a-button @click="onImportGoods">
          <ImportOutlined />
          第三步：开始导入
        </a-button>
      </div>
    </a-modal>
    </a-card>
  </template>
  <script setup>
    import { reactive, ref, onMounted } from 'vue';
    import { message, Modal } from 'ant-design-vue';
    import { SmartLoading } from '/@/components/framework/smart-loading';
    import { enterpriseApi } from '/@/api/business/oa/enterprise-api';
    import { PAGE_SIZE, PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
    import { useRouter } from 'vue-router';
    // import EnterpriseOperate from './components/enterprise-operate-modal.vue';
    import { smartSentry } from '/@/lib/smart-sentry';
    import { defaultTimeRanges } from '/@/lib/default-time-ranges';
    import TableOperator from '/@/components/support/table-operator/index.vue';
    import { TABLE_ID_CONST } from '/@/constants/support/table-id-const';
    import {plateNumberApi} from '/@/api/licensePlate/transit/plateNumber';
    import Form from './components/form.vue';
    import * as XLSX from 'xlsx';
    import { saveAs } from 'file-saver';
  
    // --------------------------- 企业表格 列 ---------------------------
    function whitelistIpFn(record){
      console.log(record.cameraDevicesVOList,'record')
      if(record.cameraDevicesVOList&&record.cameraDevicesVOList.length){
        let arr  = record.cameraDevicesVOList.map(i=>{
            return  i.camName
        })
        console.log(arr,'arr')
        return arr.join(',')
        // return record.cameraDevicesVOList.map(i=> i.camName+':'+i.camIp).json(',') 
      }
      return ''
      
    }
    const columns = ref([
      {
        title: '车辆属性',
        dataIndex: 'carCode',
        width:80,
        ellipsis: true,
      },
      {
        title: '白名单',
        dataIndex: 'whitelistIp',
        // minWidth: 170,
        ellipsis: true,
      },
      {
        title: '车牌号',
        dataIndex: 'carPlate',
        width:100,
        ellipsis: true,
      },
      {
        title: '归属单位/个人名称',
        dataIndex: 'cmpName',
        width:150,
      },
      {
        title: '车辆状态',
        width: 80,
        dataIndex: 'status',
        ellipsis: true,
      },
      {
        title: '车辆通行开始时间',
        width: 150,
        dataIndex: 'start',
        ellipsis: true,
      },
      {
        title: '车辆通行结束时间',
        width: 150,
        dataIndex: 'end',
      },
      {
        title: '操作',
        dataIndex: 'action',
        // fixed: 'right',
        width: 100,
      },
    ]);
  
    // --------------------------- 查询 ---------------------------
  
    const queryFormState = {
      carCode: '',
      carplate:'',
      recordType:1,
      pageNum: 1,
      pageSize: PAGE_SIZE,
      // searchCount: true,
    };
    const queryForm = reactive({ ...queryFormState });
    const tableLoading = ref(false);
    const tableData = ref([]);
    const total = ref(0);
  
    // 日期选择
    let searchDate = ref();
  
    function dateChange(dates, dateStrings) {
      queryForm.startTime = dateStrings[0];
      queryForm.endTime = dateStrings[1];
    }
  
    function onSearch() {
      queryForm.pageNum = 1;
      ajaxQuery();
    }
  
    function resetQuery() {
      searchDate.value = [];
      Object.assign(queryForm, queryFormState);
      ajaxQuery();
    }
    
  
    async function ajaxQuery() {
      try {
        tableLoading.value = true;
        let responseModel = await plateNumberApi.getList(queryForm);
        const list = responseModel.data.list;
        total.value = responseModel.data.total;
        tableData.value = list;
      } catch (e) {
        smartSentry.captureError(e);
      } finally {
        tableLoading.value = false;
      }
    }
  // ---------------------------- 添加/修改 ----------------------------
  const formModal = ref();
  function addForms(fData) {
    formModal.value.showDrawer(fData);
  }
  function updateForms(fData) {
    formModal.value.showDrawer(fData);
  }
  // ------------------------------- 导出和导入 ---------------------------------
  // 下载模板
  function downloadExcel() {
    plateNumberApi.downloadTemlate({fileName:'车辆信息上传模板-车牌.xlsx'})
  }
  // 导入弹窗
  const importModalShowFlag = ref(false);

  const fileList = ref([]);
  // 显示导入
  function showImportModal() {
    fileList.value = [];
    importModalShowFlag.value = true;
  }

  // 关闭 导入
  function hideImportModal() {
    importModalShowFlag.value = false;
    onSearch()
  }
  function handleRemove(file) {
    const index = fileList.value.indexOf(file);
    const newFileList = fileList.value.slice();
    newFileList.splice(index, 1);
    fileList.value = newFileList;
  }
  function beforeUpload(file) {
    fileList.value = [...(fileList.value || []), file];
    return false;
  }
  async function onImportGoods() {
    const formData = new FormData();
    fileList.value.forEach((file) => {
      formData.append('file', file.originFileObj);
    });

    SmartLoading.show();
    try {
      let res = await plateNumberApi.import(formData);
      message.success(res.msg);
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }
    // --------------------------- 导出 ---------------------------
    let listExport = []
    async function exportExcel() {
      let tableList = await plateNumberApi.exportPlateNumber({type:'1'});
      console.log('tableList',tableList);
      try {

        listExport = tableList.data.map(item => ({
          车辆识别码: item.carCode,
          车牌: item.carPlate,
          公司名称: item.cmpName,
          车辆类型: item.carType,
          车辆状态: item.status,
          通行识别码: item.tag,
          车辆通行开始时间: item.start,
          车辆通行结束时间: item.end
        }));

        // 导出数据
        const ws = XLSX.utils.json_to_sheet(this.listExport);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
        const xlsxData = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
        const blob = new Blob([xlsxData], { type: 'application/octet-stream' });
        saveAs(blob, '车辆信息.xlsx');
        } catch (err) {
        console.error(err);
        }
    }
  
    // --------------------------- 删除 ---------------------------
  
    function confirmDelete(enterpriseId) {
      Modal.confirm({
        title: '确定要删除吗？',
        content: '删除后，该信息将不可恢复',
        okText: '删除',
        okType: 'danger',
        onOk() {
          del(enterpriseId);
        },
        cancelText: '取消',
        onCancel() {},
      });
    }
  
    async function del(enterpriseId) {
      try {
        SmartLoading.show();
        await plateNumberApi.delete(enterpriseId);
        message.success('删除成功');
        ajaxQuery();
      } catch (e) {
        smartSentry.captureError(e);
      } finally {
        SmartLoading.hide();
      }
    }
  
    // --------------------------- 详情 ---------------------------
  
    let router = useRouter();
    function detail(enterpriseId) {
      router.push({ path: '/oa/enterprise/enterprise-detail', query: { enterpriseId: enterpriseId } });
    }
  
    onMounted(ajaxQuery);
  </script>
  